package me.shan.data.structure;

/**
 * 描述：队列，链表实现
 *
 * @author liuchuang
 * @date 2021/7/6 14:12
 */
public class LinkedListQueue {

    private Node<Integer> head;

    /**
     * 往链表增加值
     *
     * @param value 待加入的值
     */
    public void add(Integer value) {
        if (head == null) {
            head = new Node<>(value);
        } else {
            Node<Integer> current = head;
            while (current.getNext() != null) {
                current = current.getNext();
            }
            current.setNext(new Node<>(value));
        }
    }

    /**
     * 删除队列首元素
     *
     * @return 被删除的值
     */
    public int remove() throws Exception {
        if (head == null) {
            throw new Exception("空队列，不支持remove操作");
        }
        int value = head.getValue();
        Node<Integer> next = head.getNext();
        head.setNext(null);
        head = next;
        return value;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("LinkedListQueue{ ");
        if (head == null) {
            stringBuilder.append("null }");
        } else {
            Node<Integer> current = head;
            while (current.getNext() != null) {
                stringBuilder.append(current.getValue());
                stringBuilder.append(", ");
                current = current.getNext();
            }
            // 增加尾节点
            stringBuilder.append(current.getValue());
            stringBuilder.append(" }");
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws Exception {
        LinkedListQueue queue = new LinkedListQueue();
        System.out.println(queue);
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        System.out.println(queue);
        queue.remove();
        queue.remove();
        System.out.println(queue);
        queue.add(5);
        queue.add(6);
        System.out.println(queue);
        queue.remove();
        queue.remove();
        queue.remove();
        queue.remove();
        queue.remove();
    }
}
